import imaplib, re
from datetime import datetime
import conf
from email import parser

import logging
logging.basicConfig(level=logging.DEBUG)

def mainImap(d):
    '''Zapisuje wiadomosci email od daty d, zwraca liste plikow'''
    ret = []    
    logging.info('logging in')
    imap = imaplib.IMAP4_SSL(conf.mail['imapurl'])    
    imap.login(conf.mail['user'], conf.mail['password'])
    logging.info('logged')
    imap.select(conf.mail['label'])

    if d != None:
        today = d.strftime('"%d-%b-%Y"')
        typ, data = imap.search(None, 'SINCE', today)
    else:
        typ, data = imap.search(None, 'ALL')

    i = 0
    for num in data[0].split():
        i = i+1
        typ, data = imap.fetch(num, '(RFC822)')
        logging.info('downloading>' + data[0][0])
        p = parser.Parser()
        date = p.parsestr(data[0][1], headersonly=1)['Date']

        date = re.match('(.*) [^ ]*$', date).group(1)
        date = datetime.strptime(date, '%a, %d %b %Y %H:%M:%S')        
        sub = date.strftime('%Y%m%d') 
        
        f = open(conf.mail['basedir'] + sub + str(i) + '.mail', 'w')
        f.write(data[0][1])
        ret.append(f.name)
        f.close()

    imap.close()
    imap.logout()
    logging.info('logging out')
    return ret
